package shortcut

import (
	"apibe/grpc/rome/v1/share/db"
	"time"
)

type Cache struct {
	Key  string `json:"key" bson:"key"`
	Hold int    `json:"hold" bson:"hold"` // 缓存时长 s
}

// CacheGet
// 获取 design 缓存数据
func (c *Cache) CacheGet() ([]byte, error) {
	bytes, err := db.CacheDBClient.Get(c.Key).Bytes()
	if err != nil {
		return nil, err
	}
	return bytes, nil
}

// CacheSet
// 设置 design 缓存数据
func (c *Cache) CacheSet(value []byte) {
	if c.Key != "" {
		expiration := time.Second * time.Duration(c.Hold)
		db.CacheDBClient.Set(c.Key, value, expiration)
	}
}

// CacheRemoveOne
// 移除 design 缓存数据
func (c *Cache) CacheRemoveOne(cache string) int64 {
	del := db.CacheDBClient.Del(cache)
	return del.Val()
}

// CacheRemoveMany
// 根据通配符移除缓存
func (c *Cache) CacheRemoveMany(cache string) int64 {
	keys := db.CacheDBClient.Keys(cache + "*").Val()
	del := db.CacheDBClient.Del(keys...)
	return del.Val()
}

// CacheRemoveAll
// 移除所有的缓存
func (c *Cache) CacheRemoveAll() int64 {
	keys := db.CacheDBClient.Keys("*").Val()
	del := db.CacheDBClient.Del(keys...)
	return del.Val()
}
